package feedback;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rules.feedback.PersonFeedbackValidator;
import books.BookInfo;
import books.BooksHandler;

/**
 * Manages the PersonFeedback's of a BookInfo.
 */
public class FeedbacksHandler {

    private BooksHandler booksHome;

    private Map<BookInfo, BookInfoFeedback> feedbacks;

    public FeedbacksHandler(final BooksHandler aBooksHome) {
        this.booksHome = aBooksHome;
        this.feedbacks = new HashMap<BookInfo, BookInfoFeedback>();
    }

    public void setHome(final BooksHandler home) {
        this.booksHome = home;
    }

    public BooksHandler getBooksHome() {
        return this.booksHome;
    }

    public void setBooksHome(final BooksHandler booksHome) {
        this.booksHome = booksHome;
    }

    public void setFeedbacks(final Map<BookInfo, BookInfoFeedback> feedbacks) {
        this.feedbacks = feedbacks;
    }

    public void addFeedback(final PersonFeedback aFeedback) {
        BookInfo info = aFeedback.getBook();
        this.validateGetBookInfo(info);
        this.validateEntry(info);
        new PersonFeedbackValidator().validate(aFeedback);
        this.getFeedbackOf(info).addUserFeedback(aFeedback);
    }

    protected BookInfoFeedback getFeedbackOf(final BookInfo aBookInfo) {
        this.validateGetBookInfo(aBookInfo);
        this.validateEntry(aBookInfo);

        return this.getFeedbacks().get(aBookInfo);

    }

    protected void validateEntry(final BookInfo aBookInfo) {
        if (!this.getFeedbacks().containsKey(aBookInfo)) {
            this.getFeedbacks().put(aBookInfo, new BookInfoFeedback(aBookInfo));
        }
    }

    protected void validateGetBookInfo(final BookInfo aBookInfo) {
        this.getHome().validateGetBookInfo(aBookInfo);
    }

    protected Map<BookInfo, BookInfoFeedback> getFeedbacks() {
        return this.feedbacks;
    }

    protected BooksHandler getHome() {
        return this.booksHome;
    }

    public List<PersonFeedback> getAllFeedbackOf(final BookInfo aBookInfo) {
        this.validateGetBookInfo(aBookInfo);
        this.validateEntry(aBookInfo);

        return this.getFeedbackOf(aBookInfo).getPeopleFeedback();
    }
}
